package nl.project.registration;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nl.project.data.Student;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;

public class Registration extends HttpServlet {

	/**
	 * If the user gets here, then they must have got here manually (without
	 * redirect from login page). So first check if the user has logged in.
	 */
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			if (req.getSession().getAttribute("user") != null) {
				doPost(req, resp);
			} else {
				// user needs to login
				resp.sendRedirect("");
			}
		} catch (ServletException e) {
			// return something like:
			// "Something went wrong! If problem stays, contact admin!"
		}
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if (validate(req)) {
			getServletContext().getRequestDispatcher("/confirmation").forward(
					req, resp);
		}

		PrintWriter out = resp.getWriter();
		int id = 0;
		try {
			id = Integer.parseInt(req.getParameter("student_id"));
			req.getSession().setAttribute("student_id", id);
		} catch (NumberFormatException e) {
			try {
				id = (Integer) req.getSession().getAttribute("student_id");
			} catch (NullPointerException f) {
				resp.sendRedirect("");
			}
		}
		HttpSession session = req.getSession();
		Student student = null; // to avoid errors below
		List<Entity> classes = null;
		try {
			student = new Student(id);
			session.setAttribute("student", student);
			DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
			Key studentKey = student.getKey();
			Query query = new Query("vak", studentKey);
			classes = ds.prepare(query).asList(
					FetchOptions.Builder.withDefaults());
		} catch (EntityNotFoundException e) {
			// return something like:
			// "Something went wrong! If problem stays, contact admin!"
		}
		out.println("<html>");
		out.println("<head>");
		out.println("<title>Selectie vakken/docenten</title>");
		out.println("<link rel='stylesheet' type='text/css' href='/include/style.css' />");
		out.println("</head>");
		out.println("<body>");
		RequestDispatcher rd = req.getRequestDispatcher("/include/header.jsp");
		rd.include(req, resp);
		out.println("<h2>" + student.getName() + "</h2>");
		out.println("<form action=\"\" method=\"POST\">");
		out.println(" <h3>Selecteer vak/docent</h3>");
		// loop through all the subjects, including teachers
		for (int i = 0; i < 3; i++) {
			out.println(" <select name=\"subject" + i + "\" >");
			out.println("  <option>---------------------</option>");
			for (int j = 0; j < classes.size(); j++) {
				out.println("  <option value=\""
						+ classes.get(j).getProperty("courseCode") + ","
						+ classes.get(j).getProperty("theacherCode") + "\">"
						+ classes.get(j).getProperty("courseName") + " | "
						+ classes.get(j).getProperty("theacherName")
						+ "</option>");
			}
			out.println(" </select><br />");
		}

		out.println(" <h3>Voorkeur tijdstip</h3>");
		out.println(" <fieldset>");
		out.println("  <input type=\"radio\" name=\"time\" value=\"no_pref\">Geen voorkeur</input><br />");
		out.println("  <input type=\"radio\" name=\"time\" value=\"early\">Vroeg in de avond</input><br />");
		out.println("  <input type=\"radio\" name=\"time\" value=\"later\">Laat in de avond</input><br />");
		out.println(" </fieldset>");

		out.println(" <input type=\"submit\" value=\"Bevestig afspraak\" />");

		out.println("</form>");

		out.println("</body>");
		out.println("</html>");
	}

	/*
	 * Validate the send form data before going to the confirmation page.
	 * 
	 * @param req: contains ...
	 */
	private boolean validate(HttpServletRequest req) {
		boolean isValid = false;
		try {
			if ((!req.getParameter("subject1").equals("---------------------")
					&& !req.getParameter("subject2").equals("---------------------") 
					&& !req.getParameter("subject0").equals("---------------------"))
					|| !req.getParameter("time").equals(null)) {
				isValid = true;
			}
		} catch (NullPointerException e) {
			// Doe niks, isValid is al false.
		}
		return isValid;
	}
}